<template>
  <div class="app-container">
    <!-- <el-row :gutter="20"> -->

    <!-- 右侧内容区域 -->
    <!-- <el-col :span="18"> -->
    <el-collapse-transition>
      <el-card v-show="isFilterVisible" class="search-wrapper">
        <el-form :inline="true" :model="selRoleListQuery">
          <el-form-item label="角色名称">
            <el-input
              v-model="selRoleListQuery.name"
              clearable
              placeholder="请输入角色名称"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-collapse-transition>
    <el-card>
      <!-- <div slot="header"></div> -->
      <div>
        <!-- 操作按钮区域 -->
        <div class="table-operations">
          <el-button
            type="primary"
            size="small"
            class="filter-trigger"
            @click="isFilterVisible = !isFilterVisible"
          >{{ isFilterVisible ? "收起" : "检索" }}
            <i
              :class="['el-icon-arrow-down', { 'is-reverse': isFilterVisible }]"
            />
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAdd"
          >新建</el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            @click="handleBatchDelete"
          >批量删除</el-button>
        </div>

        <!-- 表格区域 -->
        <el-table
          v-loading="loading"
          :data="roleLists"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column
            prop="number"
            label="编号"
            width="70"
          />
          <el-table-column
            prop="name"
            label="角色名称"
            align="center"
          />
          <el-table-column
            header-align="center"
            align="center"
            prop="isDelete"
            label="是否能删除"
          >
            <template slot-scope="scope">
              {{ scope.row.isDelete === 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="createTime" label="创建时间" align="center">
            <template slot-scope="scope">
              {{ formatCreateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" align="center">
            <template slot-scope="scope">
              {{ formatCreateTime(scope.row.updateTime) }}
            </template>
          </el-table-column> -->
          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-row :gutter="10" style="margin-top: 20px" type="flex" justify="end">
        <el-pagination
          background
          :current-page="selRoleListQuery.page"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="selRoleListQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      :title="addRoleQuery.id ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="addRoleQuery"
        :rules="rules"
        label-width="100px"
      >
        <!-- <el-row>
          <el-col :span="24">
            <el-form-item label="编号:" prop="number">
              <el-input
                v-model.number="addRoleQuery.number"
                placeholder="请输入编号"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->

        <el-row>
          <el-col :span="24">
            <el-form-item label="角色名称:" prop="name">
              <el-input
                v-model="addRoleQuery.name"
                placeholder="请输入角色名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="是否能删除:" prop="isDelete">
              <el-radio-group v-model="addRoleQuery.isDelete">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" prop="remark">
              <el-input
                v-model="addRoleQuery.remark"
                type="textarea"
                placeholder="请输入备注"
                :rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </div>
    </el-dialog>
    <!-- </el-col> -->
    <!-- </el-row> -->
  </div>
</template>

<script>
import {
  selRoleListApi,
  addRoleApi,
  updateRoleByIdApi,
  delRoleByIdApi,
  selNewRoleNumberApi,
  selMenuListApi
} from '@/api/system'
export default {
  name: 'UserManagement',
  data() {
    return {
      // 添加搜索框显示状态
      showSearch: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        realName: '',
        accountName: '',
        department: ''
      },
      // 角色列表查询参数
      selRoleListQuery: {
        page: 1,
        pageSize: 10,
        name: ''
      },

      // 表格数据
      tableData: [
        {
          accountName: '管理员',
          loginAccount: 'TVAdmin',
          role: '超级管理员',
          department: '',
          updateTime: '2025-01-21',
          createTime: '2017-04-06'
        },
        {
          accountName: '普通用户',
          loginAccount: 'user',
          role: '法律顾问',
          department: '行政中心',
          updateTime: '2024-10-18',
          createTime: '2022-10-27'
        }
      ],
      isFilterVisible: false,
      // 总条数
      total: 0,
      // 加载状态
      loading: false,
      // 对话框显示状态
      dialogVisible: false,
      // 表单对象
      addRoleQuery: {
        id: '',
        number: 1,
        name: '',
        isDelete: 1,
        remark: ''
      },
      // 角色列表
      roleLists: [],
      // 表单校验规则
      rules: {
        number: [
          { required: true, message: '请输入编号', trigger: 'blur' },
          { type: 'number', message: '编号必须为数字', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 50,
            message: '长度在 2 到 50 个字符',
            trigger: 'blur'
          }
        ],
        isDelete: [
          { required: true, message: '请选择是否可删除', trigger: 'change' }
        ],
        remark: [
          { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
        ]
      },
      // 选中的行
      selectedRows: [],
      selectedIds: [],
      // 树形控件数据和配置
      treeData: [],
      treeLoading: false,
      defaultProps: {
        children: 'children',
        label: 'label',
        disabled: 'disabled'
      },
      expandedKeys: [], // 默认展开的节点
      checkedKeys: [] // 默认选中的节点
    }
  },
  created() {
    this.selRoleList()
    this.selNewRoleNumber()
    this.getMenuTree()
  },
  methods: {
    // 获取最新的编号
    async selNewRoleNumber() {
      try {
        const res = await selNewRoleNumberApi()
        if (res.code === 1) {
          // 直接使用接口返回的最新编号
          this.addRoleQuery.number = res.data
        } else {
          this.$message.error(res.msg || '获取编号失败')
        }
      } catch (error) {
        console.error('获取编号失败:', error)
        this.$message.error('获取编号失败，请重试')
      }
    },
    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      // 找到第二个冒号的位置并截取字符串
      const secondColonIndex = time.indexOf(':', time.indexOf(':') + 1)
      return time.substring(0, secondColonIndex)
    },
    // 打开新增弹窗
    handleAdd() {
      this.dialogVisible = true
      this.resetForm()
      // 获取新的编号
      this.selNewRoleNumber()
    },
    // 打开编辑弹窗
    handleEdit(row) {
      this.dialogVisible = true
      // 只提取需要的字段
      this.addRoleQuery = {
        id: row.id,
        isDelete: row.isDelete,
        name: row.name,
        number: row.number,
        remark: row.remark || '' // 备注是可选的，如果没有则设为空字符串
      }
    },
    // 角色列表查询
    async selRoleList() {
      const res = await selRoleListApi(this.selRoleListQuery)
      console.log(res)
      this.roleLists = res.records
      this.total = res.total
    },
    // 查询按钮点击事件
    handleQuery() {
      this.selRoleListQuery.page = 1
      this.selRoleList()
    },
    // 重置按钮点击事件
    resetQuery() {
      this.selRoleListQuery = {
        page: 1,
        pageSize: 10,
        name: ''
      }
      this.selRoleList()
    },
    // 表格选择项变化
    handleSelectionChange(selection) {
      this.selectedRows = selection
      this.selectedIds = selection.map((item) => item.id)
    },
    // 删除按钮点击事件
    handleDelete(row) {
      this.$confirm('确认删除该角色吗？', '提示', {
        type: 'warning'
      })
        .then(async() => {
          const res = await delRoleByIdApi([row.id]) // 传入数组，与批量删除保持一致
          if (res.code === 1) {
            this.$message.success('删除成功')
            this.selRoleList() // 刷新列表
          } else {
            this.$message.error(res.msg || '删除失败')
          }
          // this.$message.success("删除成功");
        })
        .catch(() => {
          console.error('删除失败:', error)
          this.$message.error('删除失败，请重试')
        })
    },
    // 提交表单
    async handleSubmit() {
      this.$refs.formRef.validate(async(valid) => {
        if (valid) {
          try {
            const submitData = {
              ...this.addRoleQuery,
              isDelete: Number(this.addRoleQuery.isDelete),
              number: Number(this.addRoleQuery.number)
            }

            let res
            if (submitData.id) {
              res = await updateRoleByIdApi(submitData)
            } else {
              res = await addRoleApi(submitData)
            }

            if (res.code === 1) {
              this.$message.success(submitData.id ? '编辑成功' : '新增成功')
              this.dialogVisible = false
              this.resetForm()
              this.selRoleList()
            } else {
              this.$message.error(
                res.msg || (submitData.id ? '编辑失败' : '新增失败')
              )
            }
          } catch (error) {
            console.error('操作失败:', error)
            this.$message.error('操作失败，请重试')
          }
        }
      })
    },
    // 重置表单
    resetForm() {
      this.addRoleQuery = {
        id: '',
        number: '',
        name: '',
        isDelete: 1,
        remark: ''
      }
      this.$refs.formRef && this.$refs.formRef.resetFields()
    },
    // 格式化创建时间
    formatCreateTime(time) {
      if (!time) return ''
      // 找到第二个冒号的位置并截取字符串
      const secondColonIndex = time.indexOf(':', time.indexOf(':') + 1)
      return time.substring(0, secondColonIndex)
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.selRoleListQuery.pageSize = val
      this.selRoleList()
    },
    // 页码改变
    handleCurrentChange(val) {
      this.selRoleListQuery.page = val
      this.selRoleList()
    },
    // 关闭弹窗
    handleDialogClose() {
      this.resetForm()
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择要删除的角色')
        return
      }

      this.$confirm('确定要删除选中的角色吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          try {
            console.log(this.selectedIds)
            const res = await delRoleByIdApi(this.selectedIds)
            if (res.code === 1) {
              this.$message.success('删除成功')
              this.selectedIds = []
              this.selRoleList()
            } else {
              this.$message.error(res.msg || '删除失败')
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message.error('删除失败，请重试')
          } finally {
          }
        })
        .catch(() => {
          // 取消删除
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}
/* .demo-form-inline {
  display: flex;
  justify-content: space-between;
} */
.search-wrapper {
  margin-bottom: 16px;
}

/* 添加过渡动画样式 */
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}

.table-operations {
  margin-bottom: 16px;
}

.filter-trigger .el-icon-arrow-down {
  margin-left: 5px;
  transition: transform 0.3s;
}

.filter-trigger .el-icon-arrow-down.is-reverse {
  transform: rotate(180deg);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  align-items: center;
}

.el-button + .el-button {
  margin-left: 8px;
}

.el-button--text {
  padding: 0 8px;
}

.dialog-footer .el-button {
  width: 80px;
  height: 32px;
  padding: 0;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

/* 调整输入框样式 */
:deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
}

/* 调整单选框组的样式 */
:deep(.el-radio-group) {
  display: flex;
  gap: 16px;
}

:deep(.el-radio) {
  margin-right: 0;
}

/* 调整错误提示的位置 */
:deep(.el-form-item__error) {
  padding-top: 2px;
}

/* 调整底部按钮 */
.dialog-footer {
  text-align: center;
}

.dialog-footer .el-button {
  width: 80px;
  height: 32px;
  padding: 0;
}

/* 调整文本域的样式 */
:deep(.el-textarea__inner) {
  font-family: inherit;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;

  i {
    margin-right: 8px;
    font-size: 16px;
    color: #909399;
  }
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #f0f7ff;
  color: #409eff;
}

:deep(.el-tree-node.is-disabled > .el-tree-node__content) {
  color: #c0c4cc;
  cursor: not-allowed;
}
</style>
